#include <head.h>
// 银行账户余额
int accountBalance = 10000;

// 互斥锁，用于保护账户余额
pthread_mutex_t balanceMutex;

// 信号量，用于限制同时取款的线程数量
sem_t tellerSemaphore;

// 取款线程函数
void *withdrawThread(void *arg)
{
    int amount = *((int *)arg);
    // 等待信号量，获取取款权限
    sem_wait(&tellerSemaphore);

    // 加锁，保护账户余额
    pthread_mutex_lock(&balanceMutex);

    if (accountBalance >= amount)
    {
        printf("Thread %lu: 取款成功，取款金额为 %d\n", pthread_self(), amount);
        accountBalance -= amount;
        sleep(1);
    }
    else
    {
        printf("Thread %lu: 取款失败，账户余额不足\n", pthread_self());
        sleep(1);
    }

    // 解锁，释放账户余额
    pthread_mutex_unlock(&balanceMutex);

    // 释放信号量，允许其他线程取款
    sem_post(&tellerSemaphore);
    sleep(1);

    pthread_exit(NULL);
}



 
int main(int argc, char const *argv[])
{
    pthread_t threads[5];
    int amounts[5] = {100, 200, 300, 400, 500};

    // 初始化互斥锁
    pthread_mutex_init(&balanceMutex, NULL);

    // 初始化信号量，设置同时取款的线程数量为 2
    sem_init(&tellerSemaphore, 0, 2);

    // 创建 5 个取款线程
    for (int i = 0; i < 5; i++)
    {
        pthread_create(&threads[i], NULL, withdrawThread, &amounts[i]);
    }

    // 等待所有线程完成
    for (int i = 0; i < 5; i++)
    {
        pthread_join(threads[i], NULL);
    }

    // 销毁互斥锁和信号量
    pthread_mutex_destroy(&balanceMutex);
    sem_destroy(&tellerSemaphore);
    printf("最终账户余额: %d\n", accountBalance);

    return 0;
}
